package com.common.app.utls

import android.text.InputFilter
import android.text.Selection
import android.text.Spanned
import android.widget.EditText

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：7/4/2023
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class InputFilterMinMax : InputFilter {
    private var min: Double = 0.0
    private var max: Double = 10000.0
    private var edt: EditText? = null

    constructor(min: Double, max: Double) {
        this.min = min
        this.max = max
    }
    constructor(edt: EditText?, min: Double, max: Double) {
        this.min = min
        this.max = max
        this.edt = edt
    }

    constructor(min: String?, max: String?) {
        if (min != null) {
            this.min = min.toDouble()
        }

        if (max != null) {
            this.max = max.toDouble()
        }
    }

    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        try {
            //限制小数点位数
            if (source == "." && dest.toString().isEmpty()) {
                return "0."
            }
            if (dest.toString().contains(".")) {
                val index: Int = dest.toString().indexOf(".")
                val mlength: Int = dest.toString().substring(index).length
                if (mlength == 3) {
                    return ""
                }
            }
            //限制大小
            val input: Double = (dest.toString() + source.toString()).toDouble()
            if (isInRange(min, max, input)) return null
        } catch (nfe: Exception) {
        }
        return ""
    }

    private fun isInRange(a: Double, b: Double, c: Double): Boolean {
        return if (b > a) c in a..b else c in b..a
    }

    private fun setCusValue(mValue: String) {
        if (edt != null) {
            edt?.setText(mValue)
            val editable = edt?.text
            //新字符串的长度
            val newLen = edt?.length()
            //设置新光标所在的位置
            if (newLen != null) {
                Selection.setSelection(editable, newLen)
            }
        }
    }
}
